package rpc.trace;

/*********
 *
 *
 *@author 197
 *@date 2020/6/23 10:03
 *
 **/
public class Trace {

  private static final ThreadLocal<TraceContext> curTraceContext = ThreadLocal.withInitial(() -> new TraceContext());

  public static void clearTraceContext() {
//    System.out.println("clear traceContext");
    curTraceContext.set(null);
  }

  public static TraceContext newTraceContext() {
    TraceContext traceContext = new TraceContext();
    curTraceContext.set(traceContext);
    return traceContext;
  }

  public static TraceContext get() {
    return curTraceContext.get();
  }

  public static TraceContext getOrNew() {
    TraceContext traceContext = curTraceContext.get();
    if (traceContext != null) {
      return traceContext;
    }

    traceContext = new TraceContext();
//    System.out.println("new traceContext");
    curTraceContext.set(traceContext);
    return traceContext;
  }

  public static void resetTraceContext(TraceContext traceContext) {
    curTraceContext.set(traceContext);
  }

  public TraceContext setLogValue(String key, Object value) {
    TraceContext traceContext = Trace.getOrNew();
    traceContext.setLogValue(key, value);
    return traceContext;
  }
}